import React, { createContext } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { connect, DispatchProp } from 'dva';
import { StoreState } from '@/common/store/store';
import AddBrandPanel from './components/AddCategoryPanel';
import BrandListTable, { CategoryTableProps } from './components/CategoryListTable';

interface BrandListProps extends CategoryTableProps, DispatchProp {
  loading?: boolean;
}

export const BrandTableContext = createContext<CategoryList>({} as CategoryList);

class CategoryList extends React.Component<BrandListProps> {
  formRef!: React.Component<FormComponentProps>;

  saveFormRef = (formRef: any) => {
    this.formRef = formRef;
  };

  handleSearch = () => {
    const { form } = this.formRef.props;
    const { dispatch } = this.props;
    dispatch({
      type: 'brand/query',
      payload: form.getFieldsValue(),
    });
  };

  onRowDelete = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productCategory/remove',
      payload: id,
    });
  };

  render() {
    const { loading } = this.props;

    return (
      <div className="row-group">
        <AddBrandPanel />
        <BrandTableContext.Provider value={this}>
          <BrandListTable categories={this.props.categories} loading={loading} />
        </BrandTableContext.Provider>
      </div>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  categories: state.productCategory.categories,
  loading: state.loading.models.productCategory,
});

export default connect(mapStateToProps)(CategoryList);
